package com.ermao.mymes.service.api.impl.action;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ermao.mymes.service.api.impl.domain.SendTaskModel;
import com.ermao.mymes.common.enums.RespStatusEnum;
import com.ermao.mymes.support.pipeline.BusinessProcess;
import com.ermao.mymes.support.pipeline.ProcessContext;
import com.ermao.mymes.common.vo.BasicResultVO;
import com.google.common.base.Throwables;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;

/**
 * 发送到 MQ 的责任链处理
 * @author Ermao
 * Date: 2022/5/8 11:39
 */
@Slf4j
public class SendMqAction implements BusinessProcess {
	@Autowired
	private KafkaTemplate kafkaTemplate;

	@Value("${mymes.topic.name}")
	private String topicName;

	@Override
	public void process(ProcessContext context) {
		SendTaskModel sendTaskModel = (SendTaskModel) context.getProcessModel();
		try {
			kafkaTemplate.send(topicName, JSON.toJSONString(sendTaskModel.getTaskInfo(),
					new SerializerFeature[] {SerializerFeature.WriteClassName}));
		} catch (Exception e) {
			context.setNeedBreak(true).setResponse(BasicResultVO.fail(RespStatusEnum.SERVICE_ERROR));
			log.error("send kafka fail! e:{},params:{}", Throwables.getStackTraceAsString(e)
					, JSON.toJSONString(CollUtil.getFirst(sendTaskModel.getTaskInfo().listIterator())));

		}
	}
}
